package com.jhl.seckill.mq;

import cn.hutool.json.JSONUtil;
import com.jhl.seckill.entity.SeckillOrder;
import com.jhl.seckill.entity.User;
import com.jhl.seckill.service.GoodsMQService;
import com.jhl.seckill.service.SeckillService;
import com.jhl.seckill.vo.GoodsVo;
import com.jhl.seckill.vo.SeckillMsg;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.IOException;

//@Service
@Slf4j
public class MQReceiver {
    @Autowired
    GoodsMQService goodsMQService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SeckillService seckill;

    /**
     * 下单操作
     */

    @RabbitListener(queues = {"seckillQueue"})
    public void receive2(Channel channel, Message message, String msg) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        log.info("获取的tag===" + deliveryTag);
        log.info("接收消息===" + msg);
//        try {
//            log.info("接收消息："+msg);
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//            log.info("消息接收成功");
//        } catch (Exception e){
//            /**
//             * tag:当前的消息ID
//             * true:消息放回队列排队
//             * false:丢弃数据
//             */
//            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
////            重发消息
//            resendMessage();
//        }

        SeckillMsg seckillMsg = JSONUtil.toBean(msg, SeckillMsg.class);

        Long goodsId = seckillMsg.getGoodsId();
        User user = seckillMsg.getUser();
        GoodsVo goodsVo = goodsMQService.findGoodsVobyGoodsId(goodsId);
        if (goodsVo.getStockCount() < 1) {
            return;
        }
//        判断是否重复抢购
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);
        if (seckillOrder != null) {
            return;
        }
//        正式执行秒杀逻辑
        log.info("消费者正式执行秒杀逻辑");
        seckill.seckill(user, goodsVo);

    }

//    public void resendMessage(String exchange,String routingKey,Object obj,Message message) {
//        String messageId = message.getMessageProperties().getMessageId();
//        if(StrUtil.isNotBlank(messageId) && Convert.toInt(stringRedisTemplate.opsForValue().get(messageId)) >3) {
//            log.info("===========>>>重试三次失败后依然失败存库人工处理"+obj.toString());
//            RetrySendmsg retrySendmsg = new RetrySendmsg();
//            retrySendmsg.setExchange(message.getMessageProperties().getReceivedExchange());
//            retrySendmsg.setRoutingKey(message.getMessageProperties().getReceivedRoutingKey());
//            retrySendmsg.setMsgBody(JSONUtil.toJsonStr(obj));
//            retrySendmsg.setClassName(ClassUtil.getClassName(obj, false));
//            //TODO insert方法
//            return;
//        }
//
//        rabbitTemplate.convertAndSend(exchange, routingKey, obj, msg -> {
//            MessageProperties messageProperties = msg.getMessageProperties();
//            //设置消息ID
//            String new_messageId = Convert.toStr(UUID.randomUUID());
//            if(StrUtil.isBlank(messageId)) {
//                messageProperties.setMessageId(new_messageId);
//                messageProperties.setExpiration(Convert.toStr(TopicRabbitConfig.EXPIRATION));
//                stringRedisTemplate.opsForValue().set(new_messageId,"1");
//            }else {
//                messageProperties.setMessageId(messageId);
//                messageProperties.setExpiration(Convert.toStr(TopicRabbitConfig.EXPIRATION));
//                stringRedisTemplate.opsForValue().set(messageId, Convert.toInt(stringRedisTemplate.opsForValue().get(messageId)) + 1 + "");
//            }
//            return msg;
//        });
//    }


}
